package util

import (
	"github.com/ddliu/go-httpclient"
	"io/ioutil"
	"crypto"
	"os"
	"bufio"
	"io"
//	"path/filepath"
//	"fmt"
	"encoding/hex"
	"fmt"
)


// 下载文件
func Download(url string, filename string) error {
	res, err := httpclient.Get(url, nil)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	data, err := res.ReadAll()
	if err != nil {
		return err
	}
	err1 := ioutil.WriteFile(filename, data, 0755)
	if err1 != nil {
		return err1
	}
	return nil
}

// 计算md5
func Md5sum(filename string) (string, error) {
	md5 := crypto.MD5.New()
	f, err := os.Open(filename)
	if err != nil {
		return "", err
	}
	defer f.Close()
	r := bufio.NewReader(f)

	_, err = io.Copy(md5, r)
	if err != nil {
		return "", err
	}
	temp := hex.EncodeToString(md5.Sum(nil))
	return temp, nil
}

func ScanFiles(dirPath string) ([]string, error)  {
	files := make([]string, 0, 10)

	dirs, err := ioutil.ReadDir(dirPath)
	if err != nil {
		return files, err
	}
	PathSep := string(os.PathSeparator)
	for _, file := range dirs{
		if file.IsDir() {
			fmt.Println(file.Name())
			continue
		}
		files = append(files,  dirPath + PathSep + file.Name())
	}
	return files, nil
}
//
//func f()  {
//
//	filepath.Walk("", func(path string, f os.FileInfo, err error) {
//		if f == nil {
//			return err
//		}
//		if f.IsDir() {
//			return nil
//		}
//		return nil
//	})
//}
